package com.argrace.smart.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.adapter.SubDeviceListAdapter;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.entity.WangGuanDeviceEntity;
import com.argrace.smart.entity.ZigBeeDeviceDetailEntity;
import com.argrace.smart.model.LocalDb_DeviceNameAndRoomNameTable;
import com.argrace.smart.ui.EmptyRecycleView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/2/27.
 */

public class RuoQi_SubDeviceListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    private SubDeviceListAdapter adapter;
    private ArrayList<MineZigBeeDeviceListEntity> lists = new ArrayList<>();
    private String uuid, model;
    private int pageNo = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subdevicelist);
        init();
    }

    private void init() {
        uuid = getIntent().getStringExtra("uuid");
        model = getIntent().getStringExtra("model");
        setView();
        setTitle(true, false, "关联子设备");
        setRefreshing(true);
        onRefresh();
    }

    @SuppressLint("ResourceType")
    private void setView() {
        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SubDeviceListAdapter(lists, this);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(false);
        recyclerView.setAdapter(adapter);
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
        refreshLayout.setOnRefreshListener(this);
        adapter.setOnLoadMoreListener(this);
        adapter.setlongListeners(new SubDeviceListAdapter.OnAdapterItemLongClickListener() {
            @Override
            public void click(MineZigBeeDeviceListEntity bean, int position) {
            }
        });
        adapter.setListeners(new SubDeviceListAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(MineZigBeeDeviceListEntity bean, int position) {
                if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)) {
                    showDialog_SanWei(bean);

                } else if (bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)) {
                    showDialog_LiangWei(bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
                    showDialog_ChaZuo(bean);
                } else if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI)) {
                    showDialog_KongTiao(bean);
                } else {
                    String result = bean.getName() + ":" + bean.getUuid();
                    Intent intent = new Intent();
                    //由于窗帘是用开关标识窗帘打开和关闭而不是电源开关，特殊处理
                    if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
                        result = result + "-CurtainOperation";
                    }
                    intent.putExtra("result", result);
                    intent.putExtra("model", bean.getModel());
                    setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                    finish();
                }
            }
        });
    }

    private void showDialog_ChangJingKaiGuan(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_changjingkaiguan);
        TextView text1 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text1);
        TextView text2 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text2);
        TextView text3 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text3);
        TextView text4 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text4);
        TextView text5 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text5);
        TextView text6 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text6);
    }

    private void showDialog_KongTiao(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_changjingkaiguan);
        TextView text1 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text1);
        TextView text2 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text2);
        TextView text3 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text3);
        TextView text4 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text4);
        TextView text5 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text5);
        TextView text6 = (TextView) window
                .findViewById(R.id.dialog_changjingkaiguan_text6);
        text1.setText("空调一");
        TextPaint tp1 = text1.getPaint();
        tp1.setFakeBoldText(true);
        text2.setText("空调二");
        TextPaint tp2 = text2.getPaint();
        tp2.setFakeBoldText(true);
        text3.setText("空调三");
        TextPaint tp3 = text3.getPaint();
        tp3.setFakeBoldText(true);
        text4.setText("空调四");
        TextPaint tp4 = text4.getPaint();
        tp4.setFakeBoldText(true);
        text5.setText("空调五");
        TextPaint tp5 = text5.getPaint();
        tp5.setFakeBoldText(true);
        text6.setText("空调六");
        TextPaint tp6 = text6.getPaint();
        tp6.setFakeBoldText(true);
        text1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-1";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        text2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-2";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        text3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-3";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        text4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-4";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        text5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-5";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        text6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-6";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });

    }


    private void showDialog_ChaZuo(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_duokong);
        RelativeLayout rl1 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl1);
        RelativeLayout rl2 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl2);
        RelativeLayout rl3 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl3);
        View line = window
                .findViewById(R.id.dialog_duokong_line);
        rl1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-SwitchChildLock";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        rl2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-SwitchMultiple_1";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        rl3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-SwitchMultiple_2";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        //加粗
        TextView tx1 = (TextView) window
                .findViewById(R.id.dialog_duokong_text1);
        tx1.setText("童锁开关");
        TextPaint tp1 = tx1.getPaint();
        tp1.setFakeBoldText(true);

        TextView tx2 = (TextView) window
                .findViewById(R.id.dialog_duokong_text2);
        tx2.setText("插孔1");
        TextPaint tp2 = tx2.getPaint();
        tp2.setFakeBoldText(true);
        TextView tx3 = (TextView) window
                .findViewById(R.id.dialog_duokong_text3);
        tx2.setText("插孔2");
        TextPaint tp3 = tx3.getPaint();
        tp3.setFakeBoldText(true);
    }

    private void showDialog_LiangWei(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_duokong);
        RelativeLayout rl1 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl1);
        RelativeLayout rl2 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl2);
        RelativeLayout rl3 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl3);
        View line = window
                .findViewById(R.id.dialog_duokong_line);
        line.setVisibility(View.GONE);
        rl3.setVisibility(View.GONE);
        rl1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-Switch_1";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        rl2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-Switch_2";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        //加粗
        TextView tx1 = (TextView) window
                .findViewById(R.id.dialog_duokong_text1);
        TextPaint tp1 = tx1.getPaint();
        tp1.setFakeBoldText(true);

        TextView tx2 = (TextView) window
                .findViewById(R.id.dialog_duokong_text2);
        TextPaint tp2 = tx2.getPaint();
        tp2.setFakeBoldText(true);
    }

    private void showDialog_SanWei(final MineZigBeeDeviceListEntity bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_duokong);
        RelativeLayout rl1 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl1);
        RelativeLayout rl2 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl2);
        RelativeLayout rl3 = (RelativeLayout) window
                .findViewById(R.id.dialog_duokong_rl3);
        View line = window
                .findViewById(R.id.dialog_duokong_line);
        rl1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-Switch_1";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        rl2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-Switch_2";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        rl3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
                String result = bean.getName() + ":" + bean.getUuid() + "-Switch_3";
                Intent intent = new Intent();
                intent.putExtra("result", result);
                intent.putExtra("model", bean.getModel());
                setResult(ConstantConfigure.RESULT_SUCCESS, intent);
                finish();
            }
        });
        //加粗
        TextView tx1 = (TextView) window
                .findViewById(R.id.dialog_duokong_text1);
        TextPaint tp1 = tx1.getPaint();
        tp1.setFakeBoldText(true);

        TextView tx2 = (TextView) window
                .findViewById(R.id.dialog_duokong_text2);
        TextPaint tp2 = tx2.getPaint();
        tp2.setFakeBoldText(true);
        TextView tx3 = (TextView) window
                .findViewById(R.id.dialog_duokong_text3);
        TextPaint tp3 = tx3.getPaint();
        tp3.setFakeBoldText(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        pageNo = 1;
        getSubDevicelist();
    }

    @Override
    public void onLoadMoreRequested() {
        pageNo++;
        getSubDevicelist();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    //查询子设备列表
    private void getSubDevicelist() {
        Log.i("info", "SubDeviceListActivity.getSubDevicelist(),start,uuid = " + uuid);
        String method = "mtop.openalink.home.device.infolist";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("pageNo", pageNo);
        params.put("pageSize", "10");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                JSONObject dataObj = JSON.parseObject(transitoryResponse.data.toString());
                Logg.i("info", "子设备列表获取成功data=" + dataObj.toJSONString());
                List<MineZigBeeDeviceListEntity> beans = JSON.parseArray(dataObj.getString("deviceList"), MineZigBeeDeviceListEntity.class);
                if (beans == null || beans.size() == 0) {

                    setRefreshing(false);
                    adapter.loadMoreEnd();
//                    adapter.notifyDataSetChanged();
                } else {
                    for (int i = 0; i < beans.size(); i++) {
                        List<LocalDb_DeviceNameAndRoomNameTable> beans_local = DataSupport.where("uuid = ?", beans.get(i).getUuid()).find(LocalDb_DeviceNameAndRoomNameTable.class);
                        if (beans_local != null && beans_local.size() > 0) {
                            beans.get(i).setName(beans_local.get(0).getNickName());
                        }
                    }
                    if (pageNo == 1) {
                        lists.clear();
                        lists.addAll(beans);
                        adapter.setNewData(lists);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    } else {
                        adapter.addData(beans);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                setRefreshing(false);
                if (pageNo > 1) {
                    pageNo--;
                }
                adapter.loadMoreFail();
                Log.i("info", "获取子设备列表失败,msg = " + aError.getMsg() + aError.getCode());
            }
        });

    }
}
